package com.cyc.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步调用 completableFuture
 * 异步执行
 * 成功、失败回调
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //发起一个请求
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+" runAsync=>Void");
//        });
//        System.out.println("1111111");
//        completableFuture.get(); //获取执行结果
//        System.out.println("2222222");

        //有返回值的异步回调
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+" runAsync=>String");
            //添加错误信息
            int a = 10/0;
            return "成功";
        });
        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t->" + t);//正常的返回结果
            System.out.println("u->" + u);//错误的返回结果
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return "失败";
        }).get());
    }
}
